import fetch from 'node-fetch'

/** 返回节日数量，默认3 */
const n = 3

const url = 'https://gitee.com/Tloml-Starry/resources/raw/master/resources/json/节日日期.json'
export class example extends plugin {
    constructor() {
        super({
            name: '最近节日查询',
            dsc: '查询最近的几个节日',
            event: 'message',
            priority: 1,
            rule: [{
                reg: /^(#|\/)?节日查询$/,
                fnc: 'recentHolidays'
            }]
        });
    }

    async recentHolidays(e) {
        const RHD = getNearestHolidays(n);
        const festivalText = RHD.map((festival) => {
            return `${festival['holiday']}\n日期: ${festival['date']}\n还有 ${festival['daysUntil']} 天\n`;
        }).join('');

        return e.reply([festivalText]);
    }
}

async function getNearestHolidays(numHolidays = 3) {
    const holidays = await (await fetch(url)).json()

    let currentDate = new Date();
    let formattedCurrentDate = new Date(currentDate.toLocaleString("en-US", { timeZone: "Asia/Shanghai" })).toISOString().slice(0, 10).replace(/-/g, '') - 20000000;
    let nearestHolidays = [];
    let holidayCount = 0;

    for (const holidayDate in holidays) {
        if (holidayDate.replace(/-/g, '') >= formattedCurrentDate) {
            if (holidayCount < numHolidays) {
                const holiday = holidays[holidayDate];
                const year = holidayDate.slice(0, 2);
                const month = parseInt(holidayDate.slice(3, 5)) - 1;
                const day = holidayDate.slice(6, 8);
                const holidayDateTime = new Date('20' + year, month, day, 0, 0, 0, 0);
                const timeDiff = holidayDateTime - currentDate;
                const daysUntilHoliday = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));

                nearestHolidays.push({
                    date: holidayDate,
                    holiday: holiday,
                    daysUntil: daysUntilHoliday
                });
                holidayCount++;
            } else {
                break;
            }
        }
    }

    return nearestHolidays;
}